<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索 -->
    <el-input placeholder="请输入搜索关键字" v-model="query" class="input-with-select">
      <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
    </el-input>
    <el-button type="success" plain class="addBtn" @click="showAdd">添加用户</el-button>
    <!-- 表格 -->
    <el-table
      :data="usersList"
      stripe
      style="width: 100%">
      <el-table-column
        prop="username"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        width="180">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column
        prop="mg_state"
        label="用户状态">
        <template v-slot="obj">
          <el-switch
            v-model="obj.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleChange(obj.row.id,obj.row.mg_state)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <template>
        <el-table-column
          prop=""
          label="操作"
          v-slot='{row}'
          >
          <el-button size="mini" icon="el-icon-edit" type="primary" plain @click="showEdit(row)"></el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" plain @click="deleteUser(row.id)"></el-button>
          <el-button size="mini" icon="el-icon-check" type="success" plain @click="showAssign(row)">分配角色</el-button>
        </el-table-column>
      </template>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- 添加模态框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addVisible"
      width="40%"
      @close="handleCloseAdd"
      >
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form >
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改模态框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editVisible"
      width="40%"
      >
      <el-form ref="updateForm" :model="updateForm" label-width="80px" :rules="rules">
        <el-form-item label="用户名">
          <el-tag>{{ updateForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="updateForm.mobile"></el-input>
        </el-form-item>
      </el-form >
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色模态框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="assignVisible"
      width="40%"
      >
      <el-form ref="assignForm" :model="assignForm" label-width="80px" :rules="rules">
        <el-form-item label="用户名">
          <el-tag>{{ assignForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-select v-model="assignForm.rid" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form >
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignVisible = false">取 消</el-button>
        <el-button type="primary" @click="assignUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      query: '',
      pagenum: 1,
      pagesize: 2,
      usersList: [],
      value: true,
      total: 0,
      editVisible: false,
      updateForm: {
        username: '',
        id: '',
        email: '',
        mobile: ''
      },
      addVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      assignVisible: false,
      assignForm: {
        username: '',
        id: '',
        rid: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { type: 'email', message: '请输入有效的邮箱', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: ['blur', 'change'] }
        ]
      },
      options: []
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    async getUsersList () {
      try {
        const { data } = await this.$axios.get('users', {
          params: {
            query: this.query,
            pagenum: this.pagenum,
            pagesize: this.pagesize
          }
        })
        this.total = data.total
        this.usersList = data.users
      } catch (err) {
        console.log(err)
      }
    },
    handleCurrentChange (pagenum) {
      // console.log(pagenum)
      // console.log(this.pagenum)
      this.pagenum = pagenum
      this.getUsersList()
    },
    handleSizeChange (pagesize) {
      this.pagesize = pagesize
      this.pagenum = 1
      this.getUsersList()
    },
    search () {
      console.log(222)
      this.getUsersList()
    },
    async handleChange (id, flag) {
      try {
        const { meta } = await this.$axios.put(`users/${id}/state/${flag}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    async deleteUser (id) {
      try {
        console.log(id)
        await this.$confirm('你确定要删除么', '温馨提示', { type: 'warning' })
        const { meta } = await this.$axios.delete(`users/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.getUsersList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    showEdit (row) {
      // console.log(row)
      this.updateForm.username = row.username
      this.updateForm.id = row.id
      this.updateForm.email = row.email
      this.updateForm.mobile = row.mobile
      this.editVisible = true
    },
    async updateUser () {
      try {
        const { id } = this.updateForm
        await this.$refs.updateForm.validate()
        const { meta } = await this.$axios.put(`users/${id}`, this.updateForm)
        // console.log(res)
        if (meta.status === 200) {
          this.editVisible = false
          this.getUsersList()
          this.$message.success(meta.msg)
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    showAdd () {
      console.log(222)
      this.addVisible = true
    },
    async addUser () {
      try {
        await this.$refs.addForm.validate()
        const { meta } = await this.$axios.post('users', this.addForm)
        if (meta.status === 201) {
          // 添加新用户后再最后一页显示
          this.total++
          this.pagenum = Math.ceil(this.total / this.pagesize)
          this.getUsersList()
          this.addVisible = false
        }
      } catch (err) {
        console.log(err)
      }
    },
    handleCloseAdd () {
      // 在dialog的关闭钩子函数处理表单重置
      this.$refs.addForm.resetFields()
    },
    async showAssign (row) {
      try {
        console.log(row)
        this.assignForm.username = row.username
        this.assignForm.id = row.id
        const id = this.assignForm.id
        // 拉取角色id回显
        const { data } = await this.$axios.get(`users/${id}`)
        this.assignForm.rid = data.rid
        // 模态框显示
        this.assignVisible = true
        // 获取角色列表
        const res = await this.$axios.get('roles')
        this.options = res.data
        console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    async assignUser () {
      try {
        const { id, rid } = this.assignForm
        const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
        // console.log(res)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.assignVisible = false
        }
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.users{
  .input-with-select{
    width:300px;
    margin-top: 10px;
    margin-bottom: 10px;
  }
  .addBtn{
    margin-left: 20px;
  }
}
</style>
